package com.hoperun.product.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hoperun.product.base.MIP_BaseActivity;
import com.hoperun.product.net.IServiceImpl;
import com.hoperun.product.net.RequestServiceImpl;
import com.hoperun.product.net.WebServiceAccessUtils;
import com.hoperun.product.wgyutil.WgyUtil;
import com.hoperun.yieldmgr.R;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;

import org.json.JSONObject;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;


public class ChooseActivity extends MIP_BaseActivity implements View.OnClickListener {
    JSONObject result=null;
    private static int REQUEST_EXTERNAL_STRONGE = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose);
        this.findViewById(R.id.guanlibtn).setOnClickListener(this);
        this.findViewById(R.id.piliangbtn).setOnClickListener(this);

        TextView lab=(TextView)this.findViewById(R.id.versionlab);
        lab.setText("版本号："+WgyUtil.getVersion(this));
        RequestServiceImpl.checktupdate(mMIPHandler, IServiceImpl.updateapk);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.guanlibtn:
                Intent intent = new Intent(this, LoginActivity.class);
                startActivity(intent);
                break;
            case R.id.piliangbtn:
                Intent intent2 = new Intent(this, LoginConfirmSysActivity.class);
                startActivity(intent2);
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//根据请求是否通过的返回码进行判断，然后进一步运行程序
        if (grantResults.length > 0 && requestCode == REQUEST_EXTERNAL_STRONGE && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            writerSD();
        }

    }
    @Override
    public void onPostHandle(int requestType, Object objBody, boolean error) throws Exception {
        if (error) {
            switch (requestType) {
                case IServiceImpl.updateapk://更新
                    try {
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        if (jsonObj.getInt("Code") == 0) {

                            result = jsonObj.optJSONObject("Result");
                            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_EXTERNAL_STRONGE);
                            }//REQUEST_EXTERNAL_STRONGE是自定义个的一个对应码，用来验证请求是否通过
                            else {
                                writerSD();
                            }

                        }
                    } catch (Exception e) {

                    }
                    break;
            }
        }
    }

    public void writerSD(){
        try {
            if(result!=null) {
                int serververcode = result.getInt("androidversionCode");
                final String apkurl = result.getString("androidUrl");
                String appversioname = result.getString("androidversionName");
                int androidForced = result.getInt("androidForced");

                if (WgyUtil.getVersionCode(this) != 0
                        && serververcode > WgyUtil.getVersionCode(this)) {//要更新
                    if (androidForced == 1) {//强制更新
                        new AlertView("系统更新" + appversioname, "应用已升级，请前往更新", null, null, new String[]{"立即更新"}, this, AlertView.Style.Alert, new OnItemClickListener() {
                            @Override
                            public void onItemClick(Object o, int position) {
                                startDownload(apkurl);
                            }
                        }).show();


                    } else {
                        new AlertView(appversioname, "应用已升级，请前往更新", null, null, new String[]{"更新", "取消"}, this, AlertView.Style.Alert, new OnItemClickListener() {
                            @Override
                            public void onItemClick(Object o, int position) {
                                if (position == 0) {
                                    startDownload(apkurl);
                                }
                            }
                        }).show();
                    }

                }
            }
        }catch (Exception e){

        }

    }

    /**
     * 目标文件存储的文件名
     */
    private String  destFileDir= Environment.getExternalStorageDirectory() + "/download";
    private String destFileName = "pad.apk";
    public  void  startDownload(String url){
        String downloedurl=url;

        final KProgressHUD hud= KProgressHUD.create(this)
                .setStyle(KProgressHUD.Style.ANNULAR_DETERMINATE)
                .setLabel("正在下载")
                .setCancellable(false)
                .setMaxProgress(100)
                .show();
        OkGo.get(downloedurl)//
                .execute(new FileCallback(destFileDir, destFileName) {
                    @Override
                    public void onSuccess(File file, Call call, Response response) {
                        // 安装软件
                        hud.dismiss();
                        checkIsAndroidO(file);
                    }

                    @Override
                    public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                        BigDecimal b   =   new   BigDecimal(progress);
                        float  f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue()*100;
                        hud.setProgress((int)f1);
                    }
                });


    }


    private void checkIsAndroidO(final File file) {
        if (Build.VERSION.SDK_INT >= 26) {
            boolean b = this.getPackageManager().canRequestPackageInstalls();
            if (b) {
                installApk(file);
            } else {
                XXPermissions.with(this)
                        .permission(Permission.REQUEST_INSTALL_PACKAGES) //支持请求6.0悬浮窗权限8.0请求安装权限
                        .request(new OnPermission() {

                            @Override
                            public void hasPermission(List<String> granted, boolean isAll) {
                                if(isAll) {
                                    installApk(file);
                                }
                            }
                            @Override
                            public void noPermission(List<String> denied, boolean quick) {

                            }
                        });
            }
        } else {
            installApk(file);
        }
    }

    /**
     * 安装软件
     *
     * @param file
     */
    private void installApk(File file) {
        if(Build.VERSION.SDK_INT>=24) {//判读版本是否在7.0以上
            Uri apkUri = FileProvider.getUriForFile(this, "ccom.hoperun.yieldmgrenew.fileprovider", file);//在AndroidManifest中的android:authorities值
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
            this.startActivity(install);
        } else {
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            this.startActivity(intent);
        }

    }

}